import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

// void main() => runApp(const MyApp());
//
// class MyApp extends StatelessWidget {
//   const MyApp({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       title: '钉钉风格通讯录',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         appBarTheme: const AppBarTheme(
//           backgroundColor: Colors.white,
//           foregroundColor: Colors.black,
//           elevation: 1,
//         ),
//       ),
//       home: const DingTalkFriendList(),
//     );
//   }
// }

class Friend {
  final String name;
  final String avatar;
  final String dept;
  final bool isOnline;

  Friend({
    required this.name,
    required this.avatar,
    required this.dept,
    this.isOnline = false,
  });
}

class FriendListWidget extends StatefulWidget {
  const FriendListWidget({super.key});

  @override
  State<FriendListWidget> createState() => _FriendListWidgetState();
}

class _FriendListWidgetState extends State<FriendListWidget> {
  final List<Friend> _allFriends = [
    Friend(name: "Alice", avatar: "https://randomuser.me/api/portraits/women/1.jpg", dept: "技术部", isOnline: true),
    Friend(name: "Bob", avatar: "https://randomuser.me/api/portraits/men/2.jpg", dept: "市场部"),
    Friend(name: "Charlie", avatar: "https://randomuser.me/api/portraits/men/3.jpg", dept: "财务部", isOnline: true),
    Friend(name: "David", avatar: "https://randomuser.me/api/portraits/men/4.jpg", dept: "人力资源部"),
    Friend(name: "Eva", avatar: "https://randomuser.me/api/portraits/women/5.jpg", dept: "设计部"),
    Friend(name: "Frank", avatar: "https://randomuser.me/api/portraits/men/6.jpg", dept: "销售部"),
  ];

  late List<Friend> _filteredFriends;
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final Map<String, double> _letterPositions = {};
  String _currentLetter = '';

  @override
  void initState() {
    super.initState();
    _filteredFriends = _allFriends;
    _calculateLetterPositions();
    _scrollController.addListener(_updateCurrentLetter);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Map<String, List<Friend>> _buildGroupedFriends() {
    final groupedFriends = <String, List<Friend>>{};

    for (final friend in _filteredFriends) {
      final firstLetter = friend.name.isNotEmpty
          ? friend.name.substring(0, 1).toUpperCase()
          : "#";  // 处理空名字情况
      groupedFriends.putIfAbsent(firstLetter, () => []).add(friend);
    }

    final sortedKeys = groupedFriends.keys.toList()..sort();
    return Map.fromEntries(
        sortedKeys.map((key) => MapEntry(key, groupedFriends[key]!))
    );
  }

  void _calculateLetterPositions() {
    _letterPositions.clear();
    final groupedFriends = _buildGroupedFriends();
    final sortedLetters = groupedFriends.keys.toList()..sort();
    double position = 0;
    for (final letter in sortedLetters) {
      _letterPositions[letter] = position;
      position += 30 + (groupedFriends[letter]!.length * 68);
    }
  }

  void _updateCurrentLetter() {
    final offset = _scrollController.offset;
    final letters = _letterPositions.keys.toList()..sort();
    for (var i = letters.length - 1; i >= 0; i--) {
      if (offset >= _letterPositions[letters[i]]!) {
        if (_currentLetter != letters[i]) {
          setState(() => _currentLetter = letters[i]);
        }
        break;
      }
    }
  }

  void _filterFriends(String keyword) {
    setState(() {
      _filteredFriends = _allFriends.where((friend) {
        return friend.name.toLowerCase().contains(keyword.toLowerCase()) ||
            friend.dept.toLowerCase().contains(keyword.toLowerCase());
      }).toList();
      _calculateLetterPositions();
    });
  }

  void _jumpToLetter(String letter) {
    final position = _letterPositions[letter];
    if (position != null) {
      _scrollController.animateTo(
        position,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final groupedFriends = _buildGroupedFriends();
    final letters = groupedFriends.keys.toList()..sort();

    return Scaffold(
      appBar: AppBar(
        title: const Text('通讯录'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          _buildSearchBar(),
          Expanded(
            child: Stack(
              children: [
                ListView.builder(
                  controller: _scrollController,
                  itemCount: groupedFriends.values.fold<int>(0, (sum, list) => sum + list.length + 1),
                  itemBuilder: (context, index) {
                    int sectionIndex = 0;
                    for (final letter in letters) {
                      final sectionItemCount = groupedFriends[letter]!.length + 1;
                      if (index < sectionItemCount) {
                        return index == 0
                            ? _buildSectionHeader(letter)
                            : _buildFriendItem(groupedFriends[letter]![index - 1]);
                      }
                      index -= sectionItemCount;
                    }
                    return null;
                  },
                ),
                _buildAlphabetNav(letters),
                if (_currentLetter.isNotEmpty)
                  Center(
                    child: Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        color: Colors.black54,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        _currentLetter,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      color: Colors.grey[100],
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: '搜索',
          prefixIcon: const Icon(Icons.search),
          filled: true,
          fillColor: Colors.white,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide.none,
          ),
          contentPadding: const EdgeInsets.symmetric(vertical: 8),
        ),
        onChanged: _filterFriends,
      ),
    );
  }

  Widget _buildSectionHeader(String letter) {
    return Container(
      height: 30,
      padding: const EdgeInsets.only(left: 16),
      color: Colors.grey[100],
      alignment: Alignment.centerLeft,
      child: Text(
        letter,
        style: TextStyle(
          color: Colors.grey[600],
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildFriendItem(Friend friend) {
    return ListTile(
      onTap: () => Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ContactDetailPage(friend: friend),
        ),
      ),
      leading: Stack(
        alignment: Alignment.bottomRight,
        children: [
          CircleAvatar(
            radius: 20,
            backgroundImage: CachedNetworkImageProvider(friend.avatar),
          ),
          if (friend.isOnline)
            Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: Colors.green,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 1.5),
              ),
            ),
        ],
      ),
      title: Text(friend.name),
      subtitle: Text(friend.dept),
      trailing: IconButton(
        icon: const Icon(Icons.message_outlined, color: Colors.blue),
        onPressed: () {},
      ),
    );
  }

  Widget _buildAlphabetNav(List<String> letters) {
    return Positioned(
      right: 0,
      top: 0,
      bottom: 0,
      child: Container(
        alignment: Alignment.center,
        width: 24,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: letters.map((letter) {
            return GestureDetector(
              onTap: () => _jumpToLetter(letter),
              child: Text(
                letter,
                style: TextStyle(
                  fontSize: 12,
                  color: _currentLetter == letter ? Colors.blue : Colors.grey,
                  fontWeight: _currentLetter == letter ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class ContactDetailPage extends StatelessWidget {
  final Friend friend;

  const ContactDetailPage({super.key, required this.friend});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('联系人详情'),
        actions: [
          IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildProfileHeader(),
            _buildActionButtons(),
            _buildDetailInfo(),
          ],
        ),
      ),
    );
  }

  Widget _buildProfileHeader() {
    return Container(
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        children: [
          Stack(
            alignment: Alignment.bottomRight,
            children: [
              CircleAvatar(
                radius: 40,
                backgroundImage: CachedNetworkImageProvider(friend.avatar),
              ),
              if (friend.isOnline)
                Container(
                  padding: const EdgeInsets.all(4),
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                  child: Container(
                    width: 14,
                    height: 14,
                    decoration: BoxDecoration(
                      color: Colors.green,
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 2),
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            friend.name,
            style: const TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            friend.dept,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 16),
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildActionButton(Icons.message, "发消息", Colors.blue),
          _buildActionButton(Icons.phone, "语音", Colors.green),
          _buildActionButton(Icons.videocam, "视频", Colors.purple),
          _buildActionButton(Icons.mail, "邮件", Colors.orange),
        ],
      ),
    );
  }

  Widget _buildActionButton(IconData icon, String label, Color color) {
    return Column(
      children: [
        Container(
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(icon, color: color),
        ),
        const SizedBox(height: 8),
        Text(label, style: TextStyle(color: color)),
      ],
    );
  }

  Widget _buildDetailInfo() {
    return Container(
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildInfoItem("职位", "高级开发工程师"),
          _buildInfoItem("手机", "138-1234-5678"),
          _buildInfoItem("邮箱", "alice@company.com"),
          _buildInfoItem("地址", "中国浙江省杭州市网商路699号"),
        ],
      ),
    );
  }

  Widget _buildInfoItem(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          SizedBox(
            width: 80,
            child: Text(
              title,
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 14,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(fontSize: 16),
            ),
          ),
          Icon(Icons.chevron_right, color: Colors.grey[400]),
        ],
      ),
    );
  }
}
